package com.scut.scutzone.controller;

import com.alibaba.fastjson.JSONObject;
import com.scut.scutzone.config.HttpSessionAttribute;
import com.scut.scutzone.service.DatabaseService;
import com.scut.scutzone.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/session")
public class SessionController {

    @Autowired
    private DatabaseService databaseService;

    /**
     * @description 登录接口
     * @param session 当前会话状态
     * @param params 传入JSON格式请求体 RequestBody
     */
    @PostMapping("/login")
    @ResponseBody
    public Result login(@RequestBody Map<String, String> params,
                        HttpSession session) {

        Map.Entry<String, String> userInfo = databaseService.userLogin(params.get("username"), params.get("password"));
        session.setAttribute(HttpSessionAttribute.USER_UUID, userInfo.getKey());
        session.setAttribute(HttpSessionAttribute.USER_ID, userInfo.getValue());
        return Result.success(JSONObject.parse("{\"uuid\": \"" + userInfo.getKey() + "\", \"username\": \"" + userInfo.getValue() + "\" }"));

    }

    /**
     * @description 登出接口
     * @param session 当前会话状态
     *
     */
    @DeleteMapping("/logout")
    @ResponseBody
    public Result logout(HttpSession session) {

        if (session.getAttribute(HttpSessionAttribute.USER_UUID) != null) {
            session.setAttribute(HttpSessionAttribute.USER_UUID, null);
            session.setAttribute(HttpSessionAttribute.USER_ID, null);
        }

        return Result.success(null);
    }
}
